//
//  SWPlaceholderTextView.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/8.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit

class SWPlaceholderTextView: UITextView {

    //MARK: 属性
    /// 站位文本
    var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
            placeholderLabel.sizeToFit()
            placeholderLabel.font = self.font!
        }
    }
    
     override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        //添加通知 监听文字的改变 selector指定的方法要是用了private最好加上@objc
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
    //对象销毁时调用
    deinit{
        //移除监听
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知回调
    @objc private func textViewDidChange() {
        //有文字时隐藏
        placeholderLabel.hidden = hasText()
    }
    
    //MARK: 懒加载label
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        
        self.addSubview(label)
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        label.sizeToFit()
        //添加约束
        label.translatesAutoresizingMaskIntoConstraints = false
        self.addConstraint( NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        self.addConstraint( NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))

        return label
    }()
}
